﻿using System.Collections.Generic;
using UnityEngine;

public class HttpPool:MonoSingleton<HttpPool>
{
    public static int MaxRequest=5;
    Stack<HttpComponent> cache = new Stack<HttpComponent>();
    List<HttpRequest> queue = new List<HttpRequest>();
    Dictionary<HttpRequest, HttpComponent> currentRequest = new Dictionary<HttpRequest, HttpComponent>();

    public override void OnInitialize()
    {
        for(int i=0;i<MaxRequest;i++)
        {
            var go = new GameObject();
            go.transform.SetParent(transform);
            cache.Push( go.AddComponent<HttpComponent>());
        }
    }

    public static void AddRequest(HttpRequest request)
    {
        if (Inst.queue.Contains(request))
            return;

        Inst.queue.Add(request);
    }

    public static void RemoveRequest(HttpRequest key)
    {
        if(Inst.currentRequest.ContainsKey(key))
        {
            Inst.currentRequest[key].SetCancel();
            return;
        }

        if (!Inst.queue.Contains(key))
            return;
        Inst.queue.Remove(key);
    }

    private void Update()
    {
        StartRequest();
        RemoveRequest();
       
    }

    void StartRequest()
    {
        if (queue.Count == 0 || currentRequest.Count == MaxRequest)
            return;

        var request = queue[0];
        queue.RemoveAt(0);
        var httpComponent = cache.Pop();

        switch (request.requestType)
        {
            case RequestType.GET:
                httpComponent.Get(request.url, request.taskCompletionSource);break;
            case RequestType.POST:
                httpComponent.Post(request.url,request.form, request.taskCompletionSource); break;
            case RequestType.CREATE:
            case RequestType.DELETE:
            case RequestType.HEAD:
            case RequestType.PUT:
                break;
        }

        currentRequest.Add(request, httpComponent);
        httpComponent.StartRequest();
    }

    void RemoveRequest()
    {
        foreach (var item in currentRequest)
        {
            if (item.Value.GetState() != CompletionState.Pending)
            {
                cache.Push(item.Value);
                currentRequest.Remove(item.Key);
                break;
            }
        }
    }
}
